<template>
  <div class="orders-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>采购订单管理</span>
          <div class="header-controls">
            <el-input
              v-model="searchQuery"
              placeholder="搜索订单"
              style="width: 200px; margin-right: 10px"
            />
            <el-button type="primary" @click="handleCreateOrder">创建订单</el-button>
          </div>
        </div>
      </template>

      <el-table :data="filteredOrders" style="width: 100%">
        <el-table-column prop="orderNumber" label="订单编号" width="180" />
        <el-table-column prop="supplier" label="供应商" />
        <el-table-column prop="totalAmount" label="总金额">
          <template #default="{ row }">
            ¥{{ row.totalAmount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">{{ row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleView(row)">查看</el-button>
            <el-button 
              v-if="row.status === '待确认'"
              type="success" 
              size="small" 
              @click="handleConfirm(row)"
            >确认</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 创建订单对话框 -->
    <el-dialog v-model="dialogVisible" title="创建采购订单" width="800px">
      <el-form ref="orderFormRef" :model="orderForm" :rules="rules" label-width="100px">
        <el-form-item label="供应商" prop="supplier">
          <el-select v-model="orderForm.supplier" placeholder="选择供应商">
            <el-option
              v-for="supplier in suppliers"
              :key="supplier"
              :label="supplier"
              :value="supplier"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="产品列表" prop="products">
          <div v-for="(product, index) in orderForm.products" :key="index" class="product-item">
            <el-select v-model="product.id" placeholder="选择产品" style="width: 200px" size="small">
              <el-option
                v-for="p in availableProducts"
                :key="p.id"
                :label="p.name"
                :value="p.id"
              />
            </el-select>
            <el-input-number 
              v-model="product.quantity" 
              :min="1" 
              placeholder="数量"
              size="small"
              style="width: 120px"
            />
            <el-button type="danger" size="small" @click="removeProduct(index)">删除</el-button>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="addProduct">添加产品</el-button>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="orderForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看订单详情对话框 -->
    <el-dialog v-model="viewDialogVisible" title="订单详情" width="800px">
      <div v-if="currentOrder" class="order-details">
        <div class="detail-item"><span class="label">订单编号：</span>{{ currentOrder.orderNumber }}</div>
        <div class="detail-item"><span class="label">供应商：</span>{{ currentOrder.supplier }}</div>
        <div class="detail-item"><span class="label">总金额：</span>¥{{ currentOrder.totalAmount.toFixed(2) }}</div>
        <div class="detail-item"><span class="label">状态：</span><el-tag :type="getStatusType(currentOrder.status)">{{ currentOrder.status }}</el-tag></div>
        <div class="detail-item"><span class="label">创建时间：</span>{{ currentOrder.createTime }}</div>
        <div class="detail-item"><span class="label">备注：</span>{{ currentOrder.remark }}</div>

        <el-table :data="currentOrder.products" style="width: 100%; margin-top: 20px">
          <el-table-column prop="name" label="产品名称" />
          <el-table-column prop="quantity" label="数量" />
          <el-table-column prop="price" label="单价">
            <template #default="{ row }">¥{{ row.price.toFixed(2) }}</template>
          </el-table-column>
          <el-table-column prop="total" label="小计">
            <template #default="{ row }">¥{{ (row.price * row.quantity).toFixed(2) }}</template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useOrderStore } from '@/stores/orderStore'
import { useProductStore } from '@/stores/productStore'

const searchQuery = ref('')
const orderStore = useOrderStore()
const productStore = useProductStore()

// 在组件挂载时初始化 stores
onMounted(() => {
  orderStore.initialize()
  productStore.initialize()
})

const suppliers = [
  '北京水果批发市场', '广州水果批发市场', '山东蔬菜批发市场',
  '北京蔬菜批发市场', '河南肉制品批发市场', '山东肉制品批发市场',
  '内蒙古科尔沁牛肉', '青岛海鲜批发市场', '大连水产品交易市场'
]

// 使用 productStore 中的产品数据
const availableProducts = computed(() => productStore.products.map(p => ({
  id: p.id,
  name: p.name,
  price: p.price
})))

// 使用 orderStore 中的订单数据
const filteredOrders = computed(() => {
  if (!searchQuery.value) return orderStore.orders
  const q = searchQuery.value.toLowerCase()
  return orderStore.orders.filter(o =>
    o.orderNumber.toLowerCase().includes(q) ||
    o.supplier.toLowerCase().includes(q)
  )
})

const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const currentOrder = ref(null)
const orderFormRef = ref()
const orderForm = ref({
  supplier: '',
  products: [],
  remark: ''
})

const rules = {
  supplier: [{ required: true, message: '请选择供应商', trigger: 'change' }],
  products: [{ required: true, message: '请至少添加一个产品', trigger: 'change' }]
}

const getStatusType = status => ({
  '待确认': 'warning',
  '已确认': 'success',
  '已取消': 'info'
}[status] || 'info')

const addProduct = () => {
  orderForm.value.products.push({ id: null, quantity: 1 })
}

const removeProduct = index => {
  orderForm.value.products.splice(index, 1)
}

const handleCreateOrder = () => {
  orderForm.value = { supplier: '', products: [], remark: '' }
  dialogVisible.value = true
}

const handleView = row => {
  currentOrder.value = row
  viewDialogVisible.value = true
}

const handleConfirm = (row) => {
  ElMessageBox.confirm(`确认订单 "${row.orderNumber}" 吗？`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const updatedOrder = { ...row, status: '已确认' }
    orderStore.updateOrder(updatedOrder)
    ElMessage.success('订单已确认')
  })
}

const handleSubmit = () => {
  orderFormRef.value.validate(async (valid) => {
    if (valid) {
      const orderNumber = `PO${Date.now()}`
      const products = orderForm.value.products.map(p => {
        const product = availableProducts.value.find(ap => ap.id === p.id)
        return {
          ...product,
          quantity: p.quantity,
          total: product.price * p.quantity
        }
      })
      
      const totalAmount = products.reduce((sum, p) => sum + p.total, 0)
      
      const newOrder = {
        orderNumber,
        supplier: orderForm.value.supplier,
        products,
        totalAmount,
        status: '待确认',
        createTime: new Date().toLocaleString(),
        remark: orderForm.value.remark
      }
      
      orderStore.addOrder(newOrder)
      ElMessage.success('订单创建成功')
      dialogVisible.value = false
    }
  })
}
</script>

<style scoped>
.orders-container {
  padding: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.header-controls {
  display: flex;
  align-items: center;
}
.product-item {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
.order-details {
  padding: 20px;
}
.detail-item {
  margin-bottom: 15px;
}
.detail-item .label {
  font-weight: bold;
  margin-right: 10px;
}
</style>
